package com.zzyl.nursing.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author szc
 * @date 2025-08-11
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    ElderMapper elderMapper;

    @Autowired
    BedMapper bedMapper;

    @Autowired
    ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;


    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }


    /**
     *
     * @param idCardNo 身份证号
     * @return 根据身份证号获取老人信息
     */
    public Elder getElder(String idCardNo){
        LambdaQueryWrapper<Elder> elderWrapper=new LambdaQueryWrapper<>();
        elderWrapper.eq(Elder::getIdCardNo,idCardNo);
        return  elderMapper.selectOne(elderWrapper);
    }

    /**
     * 设置插入或者更新的elder属性
     * @param elderDb
     * @param checkInApplyDto
     * @param bed
     * @return
     */
    public Elder insertOrUpdateElder(Elder elderDb,  CheckInApplyDto checkInApplyDto, Bed bed){
        Elder elder=new Elder();
        CheckInElderDto elderDto=checkInApplyDto.getCheckInElderDto();
        Long bedId=checkInApplyDto.getCheckInConfigDto().getBedId();
        BeanUtils.copyProperties(elderDto,elder);
        //补全属性
        elder.setStatus(1);
        elder.setBedId(bedId);
        elder.setBedNumber(bed.getBedNumber());
        if (Objects.isNull(elderDb)){
            //3.2无数据则新增老人数据
            elderMapper.insert(elder);
        }else{
            //3.2老人办理过入住则更新老人数据
            elder.setId(elderDb.getId());
            elderMapper.updateById(elder);
        }
        return elder;
    }


    /**
     * 入住申请
     * @param checkInApplyDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto checkInApplyDto) {
        //老人接收对象模型
        CheckInElderDto elderDto = checkInApplyDto.getCheckInElderDto();
        // 1.校验老人是否入住
        String idCardNo = elderDto.getIdCardNo();
        //根据身份证号查询到的elder
        Elder elder = getElder(idCardNo);
        if (Objects.nonNull(elder)&&(elder.getStatus()==1||elder.getStatus()==2||elder.getStatus()==4)){
            throw new BaseException("您已入住");
        }
        //入住配置接收对象模型
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        // 2.更新床位状态为已入住
        Long bedId = checkInConfigDto.getBedId();
        Bed bed = bedMapper.selectById(bedId);
        if (bed.getBedStatus()!=0){
            throw new BaseException("该床位已被使用，请更换");
        }
        bed.setBedStatus(1);
        int row = bedMapper.updateStatusById(bed.getBedStatus(),bed.getId());
        if (row<=0){
            throw new BaseException("该床位已被使用，请更换");
        }
        // 3.新增或者更新老人
        Elder insertedOrUpdateElder = insertOrUpdateElder(elder, checkInApplyDto, bed);

        // 4.新增签约办理
        insertContract(insertedOrUpdateElder,checkInApplyDto);

        // 5.新增入住信息
        //家人列表
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        CheckIn checkIn = applyInsertCheckIn(insertedOrUpdateElder,checkInConfigDto,elderFamilyDtoList);

        // 6.新增入住配置
        insertCheckInConfig(checkIn,checkInConfigDto);


    }


    private CheckIn applyInsertCheckIn(Elder elder, CheckInConfigDto checkInConfigDto, List<ElderFamilyDto> elderFamilyDtoList) {
        CheckIn checkIn=new CheckIn();
        BeanUtils.copyProperties(elder,checkIn,"id");
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setStatus(0);
        checkIn.setRemark(JSONUtil.toJsonStr(elderFamilyDtoList));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 补全属性,添加合同
     * @param elder
     * @param checkInApplyDto
     */
    private void insertContract(Elder elder, CheckInApplyDto checkInApplyDto) {
        Contract contract=new Contract();
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        BeanUtils.copyProperties(checkInContractDto,contract);
        contract.setElderId(Math.toIntExact(elder.getId()));
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contract.setStatus(0);
        contractMapper.insertContract(contract);
    }

    /**
     * 新增入住配置
     * @param checkIn
     * @param checkInConfigDto
     */
    private void insertCheckInConfig(CheckIn checkIn, CheckInConfigDto checkInConfigDto) {
        CheckInConfig checkInConfig=new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto,checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 获取入住详情
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo selectCheckInDetailById(Long id) {
        CheckIn checkIn = this.getById(id);
        //获取老人信息
        Long elderId = checkIn.getElderId();
        CheckInElderVo elderVo = getElderVo(elderId);
        //获取老人入住配置信息
        CheckInConfigVo checkInConfigVo = getCheckInConfigVo(id);
        //获取老人家属列表
        String familyList = this.getById(id).getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(familyList, ElderFamilyVo.class);
        //获取合同
        LambdaQueryWrapper<Contract> contractLambdaQueryWrapper = new LambdaQueryWrapper<>();
        contractLambdaQueryWrapper.eq(Contract::getElderId,elderId).orderByDesc(Contract::getUpdateTime).last("limit 1");
        Contract contract = contractMapper.selectOne(contractLambdaQueryWrapper);
        return new CheckInDetailVo(elderVo,elderFamilyVoList,checkInConfigVo,contract);
    }

    /**
     * 获取入住配置信息
     * @param id
     * @return
     */
    private CheckInConfigVo getCheckInConfigVo(Long id) {
        return checkInConfigMapper.selectCheckInConfigVoById(id);
    }

    /**
     * 获取老人信息
     * @param elderId
     * @return
     */
    private CheckInElderVo getElderVo(Long elderId) {
        Elder elder = elderMapper.selectById(elderId);
        CheckInElderVo elderVo=new CheckInElderVo();
        BeanUtils.copyProperties(elder,elderVo);
        elderVo.setAge(DateUtil.ageOfNow(elder.getBirthday()));
        return elderVo;
    }
}
